﻿using Cordyceps.Micro.AuthServer.Dimain.Models;
using Microsoft.EntityFrameworkCore;

namespace Cordyceps.Micro.AuthServer.EntityFrameworkCore;

public static class ModelBuilderExtensions
{
    public static void ConfigureAuthServer(this ModelBuilder builder)
    {
        Check.NotNull(builder, nameof(builder));
        //扩展OpenIddict 数据表
        builder
            .UseOpenIddict<CordycepsOpenIddictApplications, CordycepsOpenIddictAuthorizations, CordycepsOpenIddictScopes
                , CordycepsOpenIddictTokens, Guid>();

        builder.Entity<CordycepsIdentityUser>(b =>
        {
            b.ToTable("CordycepsIdentityUser");
            // Each User can have many UserClaims
            b.HasMany(e => e.Claims)
                .WithOne(e => e.User)
                .HasForeignKey(uc => uc.UserId)
                .IsRequired();

            // Each User can have many UserLogins
            b.HasMany(e => e.Logins)
                .WithOne(e => e.User)
                .HasForeignKey(ul => ul.UserId)
                .IsRequired();

            // Each User can have many UserTokens
            b.HasMany(e => e.Tokens)
                .WithOne(e => e.User)
                .HasForeignKey(ut => ut.UserId)
                .IsRequired();

            // Each User can have many entries in the UserRole join table
            b.HasMany(e => e.UserRoles)
                .WithOne(e => e.User)
                .HasForeignKey(ur => ur.UserId)
                .IsRequired();
        });

        builder.Entity<CordycepsIdentityUserClaim>(b => { b.ToTable("CordycepsIdentityUserClaim"); });

        builder.Entity<CordycepsIdentityUserLogin>(b => { b.ToTable("CordycepsIdentityUserLogin"); });

        builder.Entity<CordycepsIdentityUserToken>(b => { b.ToTable("CordycepsIdentityUserToken"); });

        builder.Entity<CordycepsIdentityRole>(b =>
        {
            b.ToTable("CordycepsIdentityRole");
            // Each Role can have many entries in the UserRole join table
            b.HasMany(e => e.UserRoles)
                .WithOne(e => e.Role)
                .HasForeignKey(ur => ur.RoleId)
                .IsRequired();

            // Each Role can have many associated RoleClaims
            b.HasMany(e => e.RoleClaims)
                .WithOne(e => e.Role)
                .HasForeignKey(rc => rc.RoleId)
                .IsRequired();
        });

        builder.Entity<CordycepsIdentityRoleClaim>(b => { b.ToTable("CordycepsIdentityRoleClaim"); });

        builder.Entity<CordycepsIdentityUserRole>(b => { b.ToTable("CordycepsIdentityUserRole"); });
    }
}